import { DEFAULT_SYMBOL } from '@/constants/global'
import * as API from '@/constants/api'
import {
  SET_SYMBOL, SET_SERVER_AUTH, UPDATE_PENDING_ORDER, UPDATE_HISTORY_ORDER,
  UPDATE_DEALS_NOTICE, UPDATE_DEPTH_NOTICE
} from '@/constants/mutation-types'

const defaultPendingOrder = {
  offset: 0,
  limit: 50,
  total: 0,
  records: []
}
const defaultHistoryOrder = {
  allLoaded: false, // true: 数据已全部获取完毕
  offset: 0,
  limit: 10,
  records: []
}

export const state = () => ({
  symbol: DEFAULT_SYMBOL,

  serverAuthed: false, // server.auth
  pendingOrder: defaultPendingOrder,
  historyOrder: defaultHistoryOrder,

  // 最新交易
  realTimeDeals: {},

  realTimeDepth: {}
})

export const getters = {}

export const mutations = {
  [SET_SYMBOL] (state, symbol) {
    state.symbol = symbol
  },
  [SET_SERVER_AUTH] (state, bool) {
    state.serverAuthed = bool
  },
  [UPDATE_PENDING_ORDER] (state, result) {
    state.pendingOrder = result || defaultPendingOrder
  },
  [UPDATE_HISTORY_ORDER] (state, result) {
    const { offset, limit, records } = result
    let allLoaded = false
    if (records.length < limit) {
      allLoaded = true
    }
    const oldRecords = state.historyOrder.records
    if (offset > 0) {
      // 上拉加载更多
      const lastItem = oldRecords[oldRecords.length - 1]
      const position = records.findIndex(item => item.id === lastItem.id)
      state.historyOrder.records.push(...records.slice(position + 1))
    } else {
      // 初始化、下拉刷新、切换币对
      state.historyOrder.records = records
    }
    state.historyOrder.allLoaded = allLoaded
    state.historyOrder = {
      ...state.historyOrder,
      offset,
      limit
    }
  },
  [UPDATE_DEALS_NOTICE] (state, { params }) {
    const [name, data] = params
    if (!state.realTimeDeals[name]) {
      state.realTimeDeals = { ...state.realTimeDeals, [name]: data }
    } else {
      state.realTimeDeals[name].splice(0, 0, ...data)
      if (state.realTimeDeals[name].length > 100) {
        state.realTimeDeals[name].splice(100 - state.realTimeDeals[name].length)
      }
    }
  },
  [UPDATE_DEPTH_NOTICE] (state, { params }) {
    const [clean, data, symbol] = params
    if (!state.realTimeDepth[symbol] || clean) {
      const { asks, bids } = data
      state.realTimeDepth = {
        ...state.realTimeDepth,
        [symbol]: {
          asks: asks || [],
          bids: bids || []
        }
      }
    } else {
      Object.keys(data).forEach((type) => {
        if (data[type]) {
          data[type].forEach((item) => {
            const len = state.realTimeDepth[symbol][type].length
            for (let pos = 0; pos < len; pos++) {
              const cell = state.realTimeDepth[symbol][type][pos]
              if (item[1] === '0' && item[0] === cell[0]) {
                // 删除
                state.realTimeDepth[symbol][type].splice(pos, 1)
                break
              } else if (item[0] === cell[0]) {
                // 替换
                state.realTimeDepth[symbol][type].splice(pos, 1, item)
                break
              }
              if (pos === len - 1) {
                // 插入
                state.realTimeDepth[symbol][type].splice(0, 0, item)
              }
            }
          })
          if (type === 'asks') {
            state.realTimeDepth[symbol][type].sort(function (a, b) { return a[0] - b[0] })
          } else {
            state.realTimeDepth[symbol][type].sort(function (a, b) { return b[0] - a[0] })
          }
          // if (state.realTimeDepth[symbol][type].length > 50) {
          //   state.realTimeDepth[symbol][type].splice(50 - state.realTimeDepth[symbol][type].length)
          // }
        }
      })
    }
  }
}
export const actions = {
  setSymbol ({ commit }, symbol) {
    commit(SET_SYMBOL, symbol)
  },
  async createOrder ({ commit }, params) {
    await this.$axios.$post(API.CREATE_ORDER, params)
  },
  async createQuickOrder ({ commit }, params) {
    const { data } = await this.$axios.$post(API.CREATE_QUICK_ORDER, params)
    return data
  },
  async cancelOrder ({ commit }, params) {
    return await this.$axios.$post(API.CANCEL_ORDER, params)
  },
  subscribeDeals ({ state }, symbol) {
    this.$socket.subscribeDeals([symbol])
  },
  subscribeDepth ({ state }, params) {
    this.$socket.subscribeDepth(params)
  },
  queryPendingOrder ({ state }, payload) {
    this.$socket.queryOrder(payload)
  },
  queryHistoryOrder ({ commit }, payload) {
    const res = {offset: 0, records: [], limit: 10}
    commit(UPDATE_HISTORY_ORDER, res)
    this.$socket.queryHistoryOrder(payload)
  }
}
